<?php
namespace app\sw\controller;

use app\api\controller\Base;
use app\index\model\UserModel;

/**
 * Class Index
 * @package app\index\controller
 */
class Users extends Base
{

    public $currentModel = null;

    public function __construct(\think\App $app)
    {
        parent::__construct($app);
        $this->checkUserLogin();
        $this->currentModel = new UserModel();
    }



    public function getList(){
        $pageSize = input('pageSize', 20, 'intval');
        $pageNo = input('pageNo', 1, 'intval');
        $result = $this->_query(UserModel::where(['is_deleted' => 0])->with(['department'])->append(['login_time_str', 'roles', 'roles_arr'])->field("id,name,username,role,created_at,updated_at,userId, email, last_logintime,dingUserId, dept_id")->order('id desc'))->like("name",'', input())->page($pageNo, false, false, $pageSize);
        return $this->returnSuccess($result);
    }


    public function getUserRoles(){
        $roles = UserModel::ROLES_ARR;
        $result = [];
        foreach($roles as $key => $value){
            $result[] = [
                'value' => $key,
                'label' => $value,
            ];
        }
        return $this->returnSuccess($result);
    }

    public function doEdit(){

        $allowFiled = ["name", 'roles', 'password', 'username', 'dingUserId', 'dept_id'];
        // 过滤非数组中的字段
        $data = $this->request->only($allowFiled, 'post', null);        
        $id = input('id', 0, 'intval');
        $result = [];

        if($data['roles']){
            $data['role'] = implode(',', $data['roles']);
        }
        unset($data['roles']);
        if(isset($data['password']) && $data['password']){
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        if($id){
            $this->currentModel->where(['id' => $id])->update($data);
        }else{
            $this->currentModel->insert($data);
        }
        return $this->returnSuccess($result, "操作成功");
    }

    public function doDelete(){
        $ids = input('ids', '');
        if(!$ids) return $this->returnError([], '删除的数据ID有误');
        if(is_string($ids)){
            $this->currentModel->whereIn('id', explode(',', $ids))->update(['is_deleted' => 1]);
        }else{
            
            $this->currentModel->where(['id' => $ids])->update(['is_deleted' => 1]);
        }
        return $this->returnSuccess([], "删除成功");
    }

}